'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { userApi } from '@/services/api';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Monitor, Smartphone, Tablet, Trash2, Shield, Clock, MapPin } from 'lucide-react';
import { toast } from 'sonner';
import type { UserSession } from '@/lib/api';

const getDeviceIcon = (userAgent: string) => {
  const ua = userAgent.toLowerCase();
  if (ua.includes('mobile') || ua.includes('android') || ua.includes('iphone')) {
    return <Smartphone className="h-4 w-4" />;
  }
  if (ua.includes('tablet') || ua.includes('ipad')) {
    return <Tablet className="h-4 w-4" />;
  }
  return <Monitor className="h-4 w-4" />;
};

const getDeviceType = (userAgent: string) => {
  const ua = userAgent.toLowerCase();
  if (ua.includes('mobile') || ua.includes('android') || ua.includes('iphone')) {
    return '移动设备';
  }
  if (ua.includes('tablet') || ua.includes('ipad')) {
    return '平板设备';
  }
  return '桌面设备';
};

const getBrowserName = (userAgent: string) => {
  const ua = userAgent.toLowerCase();
  if (ua.includes('chrome')) return 'Chrome';
  if (ua.includes('firefox')) return 'Firefox';
  if (ua.includes('safari')) return 'Safari';
  if (ua.includes('edge')) return 'Edge';
  return '未知浏览器';
};

export default function SessionsPage() {
  const { user } = useAuth();
  const [sessions, setSessions] = useState<UserSession[]>([]);
  const [loading, setLoading] = useState(true);
  const [deletingSessionId, setDeletingSessionId] = useState<string | null>(null);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [sessionToDelete, setSessionToDelete] = useState<UserSession | null>(null);

  const fetchSessions = async () => {
    try {
      const response = await userApi.getUserSessions();
      setSessions(response.data);
    } catch (error: any) {
      toast.error(error.response?.data?.message || '获取会话列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSessions();
  }, []);

  const handleDeleteSession = async (session: UserSession) => {
    setSessionToDelete(session);
    setDeleteDialogOpen(true);
  };

  const confirmDeleteSession = async () => {
    if (!sessionToDelete) return;
    
    setDeletingSessionId(sessionToDelete.id);
    try {
      await userApi.deleteUserSession(sessionToDelete.id);
      setSessions(sessions.filter(s => s.id !== sessionToDelete.id));
      toast.success('会话已删除');
      setDeleteDialogOpen(false);
      setSessionToDelete(null);
    } catch (error: any) {
      toast.error(error.response?.data?.message || '删除会话失败');
    } finally {
      setDeletingSessionId(null);
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
      </div>
    );
  }

  const currentSession = sessions.find(s => s.is_current);
  const otherSessions = sessions.filter(s => !s.is_current);

  return (
    <div className="container mx-auto py-6 space-y-6">
      <div className="flex items-center space-x-2">
        <Shield className="h-6 w-6" />
        <h1 className="text-2xl font-bold">会话管理</h1>
      </div>

      <div className="grid gap-6">
        {/* 当前会话 */}
        {currentSession && (
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center space-x-2">
                <Shield className="h-5 w-5 text-green-600" />
                <span>当前会话</span>
              </CardTitle>
              <CardDescription>
                这是您当前正在使用的会话
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-4">
                  <div className="flex items-center space-x-2">
                    {getDeviceIcon(currentSession.user_agent)}
                    <div>
                      <p className="font-medium">{getDeviceType(currentSession.user_agent)}</p>
                      <p className="text-sm text-muted-foreground">
                        {getBrowserName(currentSession.user_agent)}
                      </p>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2 text-sm text-muted-foreground">
                    <MapPin className="h-4 w-4" />
                    <span>{currentSession.ip_address}</span>
                  </div>
                  <div className="flex items-center space-x-2 text-sm text-muted-foreground">
                    <Clock className="h-4 w-4" />
                    <span>最后活动: {typeof window !== 'undefined' ? new Date(currentSession.last_activity).toLocaleString() : new Date(currentSession.last_activity).toISOString().replace('T', ' ').split('.')[0]}</span>
                  </div>
                </div>
                <Badge variant="default">当前会话</Badge>
              </div>
            </CardContent>
          </Card>
        )}

        {/* 其他会话 */}
        <Card>
          <CardHeader>
            <CardTitle>其他会话</CardTitle>
            <CardDescription>
              您在其他设备上的登录会话
            </CardDescription>
          </CardHeader>
          <CardContent>
            {otherSessions.length === 0 ? (
              <div className="text-center py-8 text-muted-foreground">
                <Shield className="h-12 w-12 mx-auto mb-4 opacity-50" />
                <p>没有其他活跃会话</p>
                <p className="text-sm">您只在当前设备上登录</p>
              </div>
            ) : (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>设备</TableHead>
                    <TableHead>IP地址</TableHead>
                    <TableHead>最后活动</TableHead>
                    <TableHead>创建时间</TableHead>
                    <TableHead className="text-right">操作</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {otherSessions.map((session) => (
                    <TableRow key={session.id}>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          {getDeviceIcon(session.user_agent)}
                          <div>
                            <p className="font-medium">{getDeviceType(session.user_agent)}</p>
                            <p className="text-sm text-muted-foreground">
                              {getBrowserName(session.user_agent)}
                            </p>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <MapPin className="h-4 w-4 text-muted-foreground" />
                          <span>{session.ip_address}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center space-x-2">
                          <Clock className="h-4 w-4 text-muted-foreground" />
                          <span>{typeof window !== 'undefined' ? new Date(session.last_activity).toLocaleString() : new Date(session.last_activity).toISOString().replace('T', ' ').split('.')[0]}</span>
                        </div>
                      </TableCell>
                      <TableCell>
                        {typeof window !== 'undefined' ? new Date(session.created_at).toLocaleString() : new Date(session.created_at).toISOString().replace('T', ' ').split('.')[0]}
                      </TableCell>
                      <TableCell className="text-right">
                        <Button
                          variant="outline"
                          size="sm"
                          onClick={() => handleDeleteSession(session)}
                          disabled={deletingSessionId === session.id}
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            )}
          </CardContent>
        </Card>
      </div>

      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>删除会话</DialogTitle>
            <DialogDescription>
              确定要删除这个会话吗？该设备将被强制退出登录。
            </DialogDescription>
          </DialogHeader>
          {sessionToDelete && (
            <div className="py-4">
              <div className="flex items-center space-x-4 p-4 border rounded-lg">
                <div className="flex items-center space-x-2">
                  {getDeviceIcon(sessionToDelete.user_agent)}
                  <div>
                    <p className="font-medium">{getDeviceType(sessionToDelete.user_agent)}</p>
                    <p className="text-sm text-muted-foreground">
                      {getBrowserName(sessionToDelete.user_agent)} • {sessionToDelete.ip_address}
                    </p>
                  </div>
                </div>
              </div>
            </div>
          )}
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setDeleteDialogOpen(false)}
            >
              取消
            </Button>
            <Button
              variant="destructive"
              onClick={confirmDeleteSession}
              disabled={!!deletingSessionId}
            >
              {deletingSessionId ? '删除中...' : '确认删除'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}